package cn.tide.question2.service.impl;

import cn.tide.question2.dao.HobbyDao;
import cn.tide.question2.dao.PersonDao;
import cn.tide.question2.domain.Hobby;
import cn.tide.question2.domain.Person;
import cn.tide.question2.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class PersonServiceImpl implements PersonService {
    @Autowired
    PersonDao personDao;
    @Autowired
    HobbyDao hobbyDao;

    private Person person = null;

    @Override
    public Person findById(int id) {

        try {
            person = personDao.findById(id);
//        System.out.println(person);
            int[] hid = hobbyDao.findHidByPid(person.getId());

            person.setHobby(new ArrayList<Hobby>());
            for (int h:hid){
                Hobby hobby = hobbyDao.findById(h);
                person.getHobby().add(hobby);
            }

        } catch (Exception e){
            e.printStackTrace();
        }


        return person;
    }

    public void add(Person person){
//        System.out.println("yp:"+person);
        int pid = personDao.add(person);
//        person.setId(pid);
//        System.out.println("p:"+person);
        List<Hobby> hobbies = person.getHobby();
        for (int i = 0; i<hobbies.size();i++){
            String name = hobbies.get(i).getName();
            Hobby hobby = hobbyDao.findByName(name);
            hobbies.get(i).setId(hobby.getId());
        }
//        System.out.println("hhhhp:"+person);
        hobbyDao.addPersonHobby(person);
//        System.out.println("pAdd:"+person);
    }

    public void delete(int id){
        hobbyDao.deletePersonHobby(id);
        personDao.delete(id);
    }

    @Override
    public void update(Person person) {
//        System.out.println(person);
        personDao.update(person);
        hobbyDao.deletePersonHobby(person.getId());

        List<Hobby> hobbies = person.getHobby();
        for (int i = 0; i<hobbies.size();i++){
            String name = hobbies.get(i).getName();
            Hobby hobby = hobbyDao.findByName(name);
            hobbies.get(i).setId(hobby.getId());
        }

        hobbyDao.addPersonHobby(person);
    }

    @Override
    public List<Person> findAll() {

        List<Person> personList = personDao.findAll();


        for (int i=0;i<personList.size();i++){
            Person person = personList.get(i);
            List<Hobby> hobbyList = new ArrayList<Hobby>();

            int[] hidByPid = hobbyDao.findHidByPid(person.getId());
            for (int j=0;j<hidByPid.length;j++){
                Hobby hobby = hobbyDao.findById(hidByPid[j]);
                hobbyList.add(hobby);
            }

            person.setHobby(hobbyList);
        }

        return personList;
    }

}
